/**
 *监控统计 -单独开窗版本
 */
define("func/monitorStatisc", [
    "leaflet",
    "func/base",
    "control/draw",
    "control/panel",
    "plugins/linqtojs",
    "data/ajax"
], function (L) {

    L.ICT.Func.add("MonitorStatisc", {

        Class: L.Class.extend({

            _data: {
                historyChk: false,
                realtimeChk: false,
                startTime: 0,
                endTime: 0
            },

            id: 'MonitorStatisc',

            initialize: function () {
                this.ictmap = L.ict.app.ictmap;
                this.dateUtil = L.ict.app.util.dateTime;
                this.dialog = L.ict.app.util.dialog;
                this.menu = L.ict.app.menu;
                this.menuid = "ict_menu_main_jktj";
                this.config = Project_ParamConfig.monitorStatiscConfig;
                this.ajax = new L.ICT.Ajax();

                this._container = null;
                this._popPanel = null;
                this._drawPopPanel = null;
                this._resultPopPanel = null;
                this._layer = null;
                this._layerType = null;
            },

            start: function () {
                if(this._container || this._popPanel) {
                    return;
                }
                this.ictmap.OperateState.jktj = true;
                this._initUi();
                this._initEvts();
                this._container.find("input[type=radio]").eq(0).click();
                this._container.find("input[type=checkbox]").eq(0).click();
                this.menu.mainmenu.deactiveMenuExceptOne(this.menuid);
                this.menu.mainmenu.disableMenuExceptOne(this.menuid);
                this.menu.mainmenu.deactivePortInfo(); //退出港口菜单
            },

            stop: function () {
                if(this._popPanel) { this._popPanel.remove(); }
                if(this.ictmap.map.hasLayer(this._layer)) {
                    this.ictmap.map.removeLayer(this._layer);
                }
                if(this.ictmap.map.hasLayer(this._locatelayer)){
                  this.ictmap.map.removeLayer(this._locatelayer);
                }
                if(this._drawPopPanel) {
                    this._drawPopPanel.remove();
                }
                if(this._resultPopPanel) {
                    this._resultPopPanel.close();
                }
                if(this._timer) {
                    clearInterval(this._timer);
                    this._timer = null;
                }
                this.ictmap.OperateState.jktj = false;
                this.ictmap.deactivate();
                this.menu.mainmenu.deactiveMenu(this.menuid);
                this.menu.mainmenu.enableMenu();
                this._container = null;
                this._popPanel = null;
                this._drawPopPanel = null;
                this._resultPopPanel = null;
                this._layer = null;
            },

            _initUi: function () {
                var options = {
                    title: '监测统计',
                    width: 400,
                    height: 450,
                    left: 100,
                    top: 200
                };
                var content = this._container = $(this.getContentHTML());
                options.contentHTML = content;
                var pop = this._popPanel = new L.ICT.PopPanel(options);
                pop.show();
                pop.on("popPanelRemove", function () {
                    this._popPanel = null;
                    this._container = null;
                    this.stop();
                }, this);
            },

            getContentHTML: function () {
                var html = [];
                html.push('<div class="monitorStatiscContainer">');
                html.push(this.getDrawHtml());
                // html.push('<p>绘制区域：</p>');
                // html.push('<div class="form-group">');
                // html.push('<label><input type="radio" name="drawRadio" value="rect">&nbsp矩形&nbsp<img src="themes/images/model/frame/ico_rect.png">&nbsp&nbsp</label>');
                // html.push('<label><input type="radio" name="drawRadio" value="circle">&nbsp圆形&nbsp<img src="themes/images/model/frame/ico_circle.png">&nbsp&nbsp</label>');
                // html.push('<label><input type="radio" name="drawRadio" value="polygon">&nbsp多边形&nbsp<img src="themes/images/model/frame/ico_ployon.png">&nbsp&nbsp</label>');
                // html.push('<label><input type="radio" name="drawRadio" value="sector">&nbsp扇(环)形&nbsp<img src="themes/images/model/frame/ico_sector.png">&nbsp&nbsp</label>');
                // html.push('</div>');
                html.push('<hr style="margin:10px 0;">');
                html.push('<p>统计类型：</p>');
                html.push('<div class="form-group">');
                html.push('<label><input type="checkbox" name="staticType" value="realtime">区域实时船舶数量</label>');
                html.push('</div>');
                html.push('<div class="form-group">');
                html.push('<label><input type="checkbox" name="staticType" value="history">区域历史进出数量</label>');
                html.push('</div>');
                html.push('<div class="timeDiv">');
                html.push('<label>时间:</label> <input type="text" class="Wdate startTime"> <label>&nbsp至&nbsp</label> <input type="text" class="Wdate endTime">');
                html.push('</div>');
                html.push('<p class="msg"></p>');
                html.push('<div class="btnDiv">');
                html.push('<button type="button" class="okBtn">确定</button>');
                html.push('<button type="button" class="cancelBtn">取消</button>');
                html.push('</div>');
                html.push('</div>');
                return html.join("");
            },

            getDrawHtml: function () {
                var html = [];
                html.push('<div class="drawDiv">');
                html.push('<ul class="nav nav-pills">');
                html.push(' <li role="presentation" class="active draw_by_hand"><a href="#">手动绘制</a></li>');
                html.push(' <li role="presentation" class="draw_by_list"><a href="#">列表选择</a></li>');
                html.push('</ul>');
                html.push('<div class="drawContent">');
                html.push(this.getDrawByHandHtml());
                html.push('<div class="list_content" style="display:none;"></div>');
                html.push('</div>');
                html.push('</div>');
                return html.join('');
            },

            getDrawByHandHtml: function () {
                var html = [];
                html.push('<form class="hand_content form-inline" style="display:block;">');
                html.push('<div class="form-group">');
                html.push('<label><input type="radio" name="drawRadio" value="rect">&nbsp矩形&nbsp<img src="themes/images/model/frame/ico_rect.png">&nbsp&nbsp</label>');
                html.push('<label><input type="radio" name="drawRadio" value="circle">&nbsp圆形&nbsp<img src="themes/images/model/frame/ico_circle.png">&nbsp&nbsp</label>');
                html.push('<label><input type="radio" name="drawRadio" value="polygon">&nbsp多边形&nbsp<img src="themes/images/model/frame/ico_ployon.png">&nbsp&nbsp</label>');
                html.push('<label><input type="radio" name="drawRadio" value="sector">&nbsp扇(环)形&nbsp<img src="themes/images/model/frame/ico_sector.png">&nbsp&nbsp</label>');
                html.push('</div>');
                html.push('</form>');
                return html.join('');
            },

            _drawCallback: function (e) {
              var layer = e.layer;
              var layerType = e.layerType;
              this.ictmap.map.addLayer(layer);
              // 检查范围是否越界
              var bounds = layer.getBounds();
              if (L.ict.app.util.tool.isLatLngsOutExtend(bounds)){
                  this.ictmap.map.removeLayer(layer);
                  L.ict.app.util.dialog.error('错误', '您绘制的区域超出合法范围！');
                  return;
              }
              //加图层
              this._layer = layer;
              // 弹出编辑框
              if(this._drawPopPanel) {
                  this._drawPopPanel.remove();
              }
              this._drawPopPanel = new L.ICT.DrawPopPanel(layer, layerType);
              this._drawPopPanel.on("popPanelRemove", function () {
                  this._drawPopPanel = null;
              }, this);
              this._drawPopPanel.show();
              //可编辑
              if(layer.editing) {
                  layer.editing.enable();
                  layer.on("edit", function (o) {
                      this._drawPopPanel.updateContent();
                  }, this);
              }
            },

            _initEvts: function () {
                var self = this;
                var $msg =  self._container.find(".msg");
                var $drawContent = self._container.find('.drawContent');

                // 时间
                var startTime = self.dateUtil.getNewDateTimeBeforHour(self.config.rangeTime);
                startTime = self.dateUtil.formatDateHM(startTime);
                var endTime = self.dateUtil.formatDateHM(new Date());
                self._container.find(".Wdate.startTime").val(startTime);
                self._container.find(".Wdate.endTime").val(endTime);

                // 手动绘制
                self._container.find(".draw_by_hand").on("click", function () {
                    if(self.ictmap.map.hasLayer(self._layer)) {
                        self.ictmap.map.removeLayer(self._layer);
                    }
                    if(self.ictmap.map.hasLayer(self._locatelayer)){
                      self.ictmap.map.removeLayer(self._locatelayer);
                    }
                    $(this).addClass('active').siblings().removeClass('active');
                    $drawContent.find('.hand_content').css('display','block');
                    $drawContent.find('.list_content').css('display','none');
                });

                // 列表选择
                self._container.find(".draw_by_list").on("click", function () {
                    self.ictmap.deactivate();
                    if(self.ictmap.map.hasLayer(self._layer)) {
                        self.ictmap.map.removeLayer(self._layer);
                    }
                    if(self.ictmap.map.hasLayer(self._locatelayer)){
                      self.ictmap.map.removeLayer(self._locatelayer);
                    }
                    if(self._drawPopPanel) {
                        self._drawPopPanel.remove();
                    }
                    $(this).addClass('active').siblings().removeClass('active');
                    $drawContent.find('.hand_content').css('display','none');
                    $drawContent.find('.list_content').css('display','block');
                    var url = self.config.areaListUrl;
                    var data = {
                        type: 300,
                        show_status: 1,
                        pageid: 1,
                        pagecount: 999
                    };
                    self.ajax.post(url, data, true, self, function (res, err){
                        self.showAreaListRes(res && res.msg && res.msg.areas || []);
                    });
                });

                //时间
                self._container.find(".Wdate").on("click", function () {
                    var config = {
                        readOnly: true,
                        dateFmt: 'yyyy-MM-dd HH:mm',
                        alwaysUseStartDate: true,
                        maxDate: '%y-%M-%d %H:%m:%s'
                    };
                    WdatePicker(config);
                });

                //绘图
                self._container.find(".hand_content input[type=radio]").on("click", function () {
                    if(self.ictmap.map.hasLayer(self._layer)) self._layer.remove();
                    if(self._drawPopPanel) self._drawPopPanel.remove();
                    var type = $(this).val();
                    if(type == "circle") {
                        self.ictmap.activate(L.ICT.MapMouseState.CIRCLE, self._drawCallback, null, self);
                    } else if(type == "rect") {
                        self.ictmap.activate(L.ICT.MapMouseState.RECTANGLE, self._drawCallback, null, self);
                    } else if(type == "polygon") {
                        self.ictmap.activate(L.ICT.MapMouseState.POLYGON, self._drawCallback, null, self);
                    } else if(type == "sector") {
                        self.ictmap.activate(L.ICT.MapMouseState.SECTOR, self._drawCallback, null, self);
                    }

                });

                //选择模式
                self._container.find("input[type=checkbox]").on("change", function () {
                    var allchks = self._container.find("input[type=checkbox]");
                    allchks.each(function () {
                        if(this.value == "realtime") {
                            if(this.checked == true) self._data.realtimeChk = true;
                            else self._data.realtimeChk = false;
                        }
                        if(this.value == "history") {
                            if(this.checked == true) {
                                self._data.historyChk = true;
                                self._container.find(".timeDiv").css("display", "block");
                            } else {
                                self._data.historyChk = false;
                                self._container.find(".timeDiv").css("display", "none");
                            }
                        }
                    });
                });

                //确定
                self._container.find(".okBtn").on("click", function () {
                    var startTime = self._container.find(".startTime").val();
                    var endTime = self._container.find(".endTime").val();
                    $msg.html("");
                    //检查
                    if(self._drawPopPanel) {
                        $msg.html("请确认绘制区域！");
                        return;
                    }
                    if(!self.ictmap.map.hasLayer(self._layer)) {
                        $msg.html("请绘制或选择区域！");
                        return;
                    }
                    if(!self._data.realtimeChk && !self._data.historyChk) {
                        $msg.html("请选择统计方式！");
                        return;
                    }
                    if(self._data.historyChk) {
                        //判断时间
                        var startTime = self._container.find(".startTime").val();
                        var endTime = self._container.find(".endTime").val();
                        var checkRes = self.dateUtil.checkStrartEndTime(startTime + ":00", endTime + ":00", 7);
                        if(!checkRes.result) {
                            $msg.text(checkRes.msg);
                            return;
                        }
                        self._data.startTimeWdate = startTime;
                        self._data.endTimeWdate = endTime;
                        self._data.startTime = self.dateUtil.getCusUnixTime(startTime + ":00");
                        self._data.endTime = self.dateUtil.getCusUnixTime(endTime + ":00");
                    }
                    self._data.mode = Project_ParamConfig.CurrentMode;
                    var bounds = self._layer.getBounds();
                    // 取多边形点
                    var data = {};
                    self._data.areaType = 'rect';
                    if(self._layer instanceof L.Circle) {
                        self._data.areaType = 'circle';
                        data.cirlon = self._layer.getLatLng().lng;
                        data.cirlat = self._layer.getLatLng().lat;
                        data.radius = self._layer.getRadius();
                    } else if (self._layer instanceof L.Rectangle) {  // 矩形实例同样也是多边形实例，故矩形必须写在前面
                        self._data.areaType = 'rect';
                        data.sw = {
                            lng: bounds.getSouthWest().lng,
                            lat: bounds.getSouthWest().lat
                        };
                        data.ne = {
                            lng: bounds.getNorthEast().lng,
                            lat: bounds.getNorthEast().lat
                        };
                    } else if(self._layer instanceof L.Polygon) {
                        self._data.areaType = 'polygon';
                        var lonarr = [],
                            latarr = [];
                        var latlngs = self._layer.getLatLngs()[0];
                        for(var i = 0, len = latlngs.length; i < len; i++) {
                            lonarr.push(latlngs[i].lng);
                            latarr.push(latlngs[i].lat);
                        }
                        lonarr.push(latlngs[0].lng);
                        latarr.push(latlngs[0].lat);
                        data.lonStrArr = lonarr.join('~');
                        data.latStrArr = latarr.join('~');
                    } else if (self._layer instanceof L.Sector) {
                       self._data.areaType = 'sector';
                       data.lon = self._layer.getLatLng().lng;
                       data.lat = self._layer.getLatLng().lat;
                       data.radius = self._layer.getMaxRadius();
                       data.radsmal = self._layer.getMinRadius();
                       data.startDeg = self._layer._startAngle < 270 ? self._layer._startAngle + 90 : self._layer._startAngle - 270;
                       data.endDeg = self._layer._endAngle < 270 ? self._layer._endAngle + 90 : self._layer._endAngle - 270;
                       data.limit = 0;
                    }
                    self._data.areaPoint = data;
                    self._data.bounds = {};
                    self._data.bounds.sw = {
                        lng: bounds.getSouthWest().lng,
                        lat: bounds.getSouthWest().lat
                    };
                    self._data.bounds.ne = {
                        lng: bounds.getNorthEast().lng,
                        lat: bounds.getNorthEast().lat
                    };
                    L.ict.app.localStorage.setItem(self.id + '_data', self._data);
                    //分析
                    if(self._data.realtimeChk) {
                        self.analysis();
                    }
                    var url = 'resultpage/monitorRes.html?' + L.stamp({});
                    self.openResultWindow(url);
                    if(self._popPanel) {
                        self._popPanel.close();
                    }
                });

                //取消
                self._container.find(".cancelBtn").on("click", function () {
                    self.stop();
                });
            },

            // 显示区域列表
            showAreaListRes:function (data){
                var $container = this._container;
                var $arealist = $container.find('.drawContent').find('.list_content');
                this._arealistData = data;
                var html = [];
                var $listDiv = $('<div class="listDiv"></div>');
                html.push('<ul class="listul">');
                for (var i = 0, len = data.length; i < len; i++){
                    html.push('<li data-id = "' + data[i]['properties']['id'] + '">');
                    html.push('<label><input type="radio" name="areaSelect">&nbsp&nbsp' + data[i]['properties']['name'] + '</label>');
                    html.push('<button type="button" class="btn btn-link areaLocate">定位</button>');
                    html.push('</li>');
                }
                html.push('</ul>');
                $listDiv.html(html.join(''));
                $arealist.html($listDiv);
                $listDiv.mCustomScrollbar({ theme: "minimal-dark", axis:'y'});
                this._initAreaListEvt($arealist);
            },

            _initAreaListEvt:function ($arealist) {
                // 选择
                $arealist.find('input[name="areaSelect"]').on('click', function (e) {
                    var id = $(e.currentTarget).parent().parent().data('id');
                    var areaInfo = this.getAreaDataById(id);
                    if (!areaInfo) return;
                    if(this.ictmap.map.hasLayer(this._layer)){
                      this.ictmap.map.removeLayer(this._layer);
                    }
                    if(this.ictmap.map.hasLayer(this._locatelayer)){
                      this.ictmap.map.removeLayer(this._locatelayer);
                    }
                    this._layer = L.ict.app.util.tool.convertGeoJsonToLeafletLayer(areaInfo);
                    this.ictmap.map.addLayer(this._layer);
                }.bind(this));

                // 定位
                $arealist.find('.areaLocate').on('click', function (e) {
                    var id = $(e.currentTarget).parent().data('id');
                    var chk = $(e.currentTarget).parent().find('input[name="areaSelect"]')[0].checked;
                    var areaInfo = this.getAreaDataById(id);
                    if (!areaInfo) return;
                    if(this.ictmap.map.hasLayer(this._locatelayer)){
                      this.ictmap.map.removeLayer(this._locatelayer);
                    }
                    // 定位图层
                    if (chk) {
                      this.ictmap.map.fitBounds(this._layer.getBounds());
                    } else {
                      this._locatelayer = L.ict.app.util.tool.convertGeoJsonToLeafletLayer(areaInfo);
                      this.ictmap.map.addLayer(this._locatelayer);
                      this.ictmap.map.fitBounds(this._locatelayer.getBounds());
                    }
                }.bind(this));
            },

            getAreaDataById:function (id) {
                if (this._arealistData && this._arealistData.length) {
                    for (var i = 0, len = this._arealistData.length; i < len; i++){
                        if (this._arealistData[i]['properties']['id'] === Number(id)) {
                            return this._arealistData[i];
                        }
                    }
                }
            },

            openResultWindow: function (url) {
                if(this._resultPopPanel) {
                    this._resultPopPanel.close();
                }
                this._resultPopPanel = window.open(url, '_blank', 'width=1060,height=600,left=500,top=200,menubar=no'); //toolbar=no,location=no,resizable=no,status=no
                if(window.focus) { this._resultPopPanel.focus(); }
                this._resultPopPanel.onunload = function () {
                    // to do 事件触发不正常，当调用window.open并带有url参数时触发
                    // this.stop();
                }.bind(this);
            },

            analysis: function () {
                this.getTargets();
                this._timer = setInterval(function () {
                    this.getTargets();
                }.bind(this), this.config.updateTime);
            },

            getTargets: function () {
                var targets = this.ictmap.realtarget.getTargetsInExtend(this._layer);
                var ts = [];
                for(var i = 0, len = targets.length; i < len; i++) {
                    var obj = L.extend({}, targets[i]);
                    obj.lat = L.ict.app.util.tool.latlngTodfmStr(obj.lat, 'lat');
                    obj.lon = L.ict.app.util.tool.latlngTodfmStr(obj.lon, 'lng');
                    obj.time = this.dateUtil.getTimeStrFromUnix(obj.time);
                    obj.infotype = this.ictmap.realtarget.getDetialConvertName(obj.infotype, 'orig_info_type');
                    obj.infosrc = this.ictmap.realtarget.getDetialConvertName(obj.infosrc, 'orig_info_source');
                    ts.push(obj);
                }
                L.ict.app.localStorage.setItem(this.id, ts);
            }
        })

    });

});
